<?php

namespace app\home\controller;

use app\home\model\Idfa724Model;
use app\home\model\Order;
use app\home\service\NotifyService;
use app\home\service\OrderService;
use think\Db;
use think\Model;
use think\Request;
use think\response\Json;

class Pay818 extends BasePay{

    public function order()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 

        parent::order();
        $data = [
            'bill_no'=>$this->order_array['id'],
            'total_fee'=>$this->order_array['amount'],
            'product_id'=>$this->order_array['goods_id'],
            'product_name'=>$this->order_array['goods_name'],
            'product_desc'=>$this->order_array['goods_name'],
        ];
        $data_Arr = [
            'code'=>200,
            'msg'=>'success',
            'data'=>$data,
        ];
        putsuccess($data_Arr);
    }

    public function notify()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 

        //TODO 前期先不走验证数据  后期走的时候可用refresh_token这个数值刷新access_tokne 以下是根据code获取的token的原始数据 保留  用于后期支付数据验证
        // {
            // "access_token": "ya29.a0ARrdaM96dQ560fxnVpro6eQJg4N9B6HgisRyhKcosEmF54Ey8RDoq1WkhFg75nF4o6JN6D2l2Q2GgObUPuLXw85NXdmnofUccbvz59S4ugFivPDqrh4m9cTStwSXlLggiwGyjQ5Zt7IQMgCAb9D2OvZc_8gn",
            // "expires_in": 3599,
            // "refresh_token": "1//0gSB54uZeVPRVCgYIARAAGBASNwF-L9Ir1B0y4qK8Hqr3qWjJfBWIIEBqafOvoWAszrO2J8ELiyGiDhdJqsjlMgnNzs99aMBx2Ag",
            // "scope": "https://www.googleapis.com/auth/androidpublisher",
            // "token_type": "Bearer"
        // }
        // $url = 'https://androidpublisher.googleapis.com/androidpublisher/v3/applications/com.cpshemagame.jcgame/purchases/products/7085/tokens/oojepcomcbmgmpehpdijmmop.AO-J1OzJo9fq3x2WK5XcNL4qP4JkvTCMMOGM9rHx3mxKgdXVOSWxJRCBniV2TuFSxvsbPDcdE5ZBd0kqAuZhHVkgHQhlx_-kGdDtx8Y3xq2s26uh6L2iRQQ?access_token=ya29.a0AVA9y1s128ChbHjxZg0YNc24APUxoyLu8qHud1dYQysPnoGlBqnEAKFgCr9t5tEuI6d8Mp3eB6waao-NhT_K79-n1NO4Ra7LYikKK4mHr6XTG4C3hoMq_nbMQ9qXy-z0k5OGjMRytM_OblDMw6XIJsp3zQxFcqs';
        // $res = $this->get($url);
        // var_dump($res);die;
        parent::notify();
        $params = $this->params;
        mylog($params);
        try{
            if (empty($params['originalData'])){
                throw new \Exception('originalData false');
            }

            //查询谷歌订单是否支付
            $originalData = json_decode($params['originalData'],true);
            $obj = $this->verifyOrder($originalData);
            $google_data =  json_decode($obj,true);
            mylog($google_data);
            //已经购买
            if($google_data['purchaseState'] !=0){
                throw new \Exception('google_data purchaseState false');
            }
            //保存订单号
            $tradeLog = (new \app\home\model\TradeLog)->where(['id'=>$google_data['obfuscatedExternalAccountId']])->find();
            if (!$tradeLog){
                throw new \Exception('google_data obfuscatedExternalAccountId false');
            }
            $obfuscatedExternalProfileId =json_decode($google_data['obfuscatedExternalProfileId'],true);//{"rmPrice":"6","type":"US","dollPrice":"0.99"}
            $tradeLog->dollPrice = $obfuscatedExternalProfileId['dollPrice'];
            $tradeLog->dollPriceType = $google_data['regionCode'];
            $tradeLog->transactionID = $google_data['orderId'];
            $tradeLog->extra = $params['originalData'];
            $tradeLog->save();

            //效验订单
            $notifyService = new NotifyService();
            $order_info = $notifyService->checkOrder($google_data["obfuscatedExternalAccountId"],$google_data["obfuscatedExternalProfileId"]);
            if($order_info == false){
                throw new \Exception('checkOrder false');
            }
            if ($order_info["status"] == OrderService::PAY_STATUS_PAID) {
                mylog("818 订单已经处理过了 订单id".$order_info['id']);
                return "SUCCESS";
            }
            
            if ($tradeLog->status == OrderService::PAY_STATUS_PAID) {
                mylog("818 订单已经处理过了 订单id".$tradeLog->id);
                return "SUCCESS";
            }

            //发货
            $notifyService = new NotifyService();
            if($notifyService->notifyProcess($tradeLog) == false){
                throw new \Exception('notifyProcess false');
            }
            return "SUCCESS";
        }catch (\Exception $exception){
            mylog('818-error:'.$exception->getMessage().' line:'.$exception->getLine().' file:'.$exception->getFile());
            return 'FAIL';
        }

    }

    //订单效验
    public function verifyOrder($data){
        // $packageName = 'com.cpshemagame.jcgame';
        // $productId = '7085';
        // $purchaseToken = 'oojepcomcbmgmpehpdijmmop.AO-J1OzJo9fq3x2WK5XcNL4qP4JkvTCMMOGM9rHx3mxKgdXVOSWxJRCBniV2TuFSxvsbPDcdE5ZBd0kqAuZhHVkgHQhlx_-kGdDtx8Y3xq2s26uh6L2iRQQ';
        $packageName = $data['packageName'];
        $productId = $data['productId'];
        $purchaseToken = $data['purchaseToken'];

        //那老海外数据库的token  等老海外不用的了在新的定时任务刷新token 到时候在哪新的数据库
        $google = db('google_token', 'db_operatelog')->find();
        //  $google = db('google_token', 'db_operatelog_old')->find();

        $access_token = $google['access_token'];
        $url = 'https://androidpublisher.googleapis.com/androidpublisher/v3/applications/'.$packageName.'/purchases/products/'.$productId.'/tokens/'.$purchaseToken.'?access_token='.$access_token;
        $res = $this->get($url);
        return  $res;
    }

    public function test(){
        $google = db('google_token', 'db_operatelog')->find();
var_dump($google['access_token']);die;
        // var_dump(env('DATABASE.hostname'));die;
                // $google = db('google_token', 'db_operatelog_old')->find();

                // var_dump($google);die;
        $res = 'https://androidpublisher.googleapis.com/androidpublisher/v3/applications/com.maniawin.hmgame/purchases/products/1010/tokens/eojnmkhceiiijkdlgnpmoied.AO-J1OytVCdGI3MMoGJSlPM2pzQfraT69q9VM85uMTRGPpiteY2X6lk_4m4GiI61hK0gou65yF_FN37uYxg7uoKrsMCnEf7qrA?access_token=ya29.a0Aa4xrXM_WRdCVI3TR0Xa01092q3WLsrtViYnAtiDNz9Fy2iIeAHA7hz1Licj6jSUKCpqI6SKEUIjXtThrsYItlkGZcI1sjH1xXaHTLJnksORnaYpL_2NYRXMEE7xkPp8KEikL_J3wPkedm9sdI0RxcJrE7Kd5MgaCgYKATASARASFQEjDvL9JU_PH_-y6Dax3TvW3zOirg0166';
        // $a = $this->get($res);
        $res = curl_get($res);
        var_dump($res);die;
    }
    public function get($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        //TODO 证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
       
        $response = curl_exec($ch);
        curl_close($ch);
        mylog($response);
        return $response;
    }


    public function refresh_token(){
        $header = [
            "Content-Type:" . "application/x-www-form-urlencoded",
        ];
        $url = 'https://accounts.google.com/o/oauth2/token';
        $content =[
            'grant_type'=>'refresh_token',
            'client_id'=>'941255985823-mvp9f7hr68euckou3n27mietpdnilgkf.apps.googleusercontent.com',
            'client_secret'=>'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',
            'refresh_token'=>'1//0gSB54uZeVPRVCgYIARAAGBASNwF-L9Ir1B0y4qK8Hqr3qWjJfBWIIEBqafOvoWAszrO2J8ELiyGiDhdJqsjlMgnNzs99aMBx2Ag'
        ];
        $clIEntID = urlencode($content['client_id']);
        $clIEntSecret = urlencode($content['client_secret']);
        $refreshToken = urlencode($content['refresh_token']);
        $content = "grant_type=refresh_token&client_id=$clIEntID&client_secret=$clIEntSecret&refresh_token=$refreshToken";

        $res = $this->post($url,$content);
        var_dump($res);die;
    }
    private function post($url, $content)
    {

        $header[0] = 'Content-Type: application/x-www-form-urlencoded';

       $ch = curl_init();
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       curl_setopt($ch, CURLOPT_URL, $url);
       curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
       curl_setopt($ch, CURLOPT_POST, true);
       curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
       //TODO 证书
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
       curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
       $response = curl_exec($ch);
       if ($error = curl_error($ch)) {
           die($error);
       }
       curl_close($ch);
       return $response;
    }
}
